<!--
 * @Descripttion: 订单管理
 * @version:
 * @Author: 赵致喜
 * @Date: 2020-10-12 18:48:41
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-26 19:07:10
-->
<template>
	<div class="organization">
		<el-form label-position="'right'" label-width="120px" label-suffix=":">
			<el-col :span="6">
				<el-form-item label="下单时间">
					<el-date-picker type="daterange" v-model="searchFormData.createTime" size="mini" clearable style="width: 100%;" />
				</el-form-item>
			</el-col>
			<el-col :span="6">
				<el-form-item label="订单编号">
					<el-input type="text" v-model="searchFormData.orderNo" size="mini" clearable />
				</el-form-item>
			</el-col>
			<el-col :span="6">
				<el-form-item label="供应商">
					<el-select v-model="searchFormData.supplierId" filterable placeholder="请选择" clearable size="mini" @change="changeSupplier">
						<template v-for="item in supplierList">
							<el-option v-if="item.supplierId != ''" :value="item.supplierId" :label="item.orgNameZh" >
							</el-option>
						</template>
					</el-select>
				</el-form-item>
			</el-col>
			<!-- <el-col :span="6">
				<el-form-item label="订单名称">
					<el-input type="text" v-model="searchFormData.orderName" size="mini" clearable />
				</el-form-item>
			</el-col> -->
			<!-- <el-col :span="6">
				<el-form-item label="电商订单号">
					<el-input type="text" v-model="searchFormData.eshopNumber" size="mini" clearable />
				</el-form-item>
			</el-col> -->
			<!-- <el-col :span="10">
				<el-form-item label="采购组织">
					<el-select v-model="searchFormData.orgName" filterable placeholder="请选择" ref="selectReport" clearable @change="clear();">
						<el-option :value="searchFormData.orgId" :label="searchFormData.orgName" style="width:100%; background-color: #fff;height: auto;overflow-y: scroll;" >
							<el-tree ref="space" :data="treeData" :check-on-click-node="false"
								:expand-on-click-node="false" :props="defaultProps" :filter-node-method="filterNode"
								@node-click="changeTree" lazy :default-expand-all="false" :load="loadNode"
								style="width: 100%; display: inline-block;">
								<span class="custom-tree-node" slot-scope="{ node }">
									<span>{{ node.label }}</span>
								</span>
							</el-tree>
						</el-option>
					</el-select>
				</el-form-item>
			</el-col> -->
			<!-- <el-col :span="2">
				<el-form-item label="是否本级">
					<el-checkbox-group @change="changeType" v-model="searchFormData.type" style="height:40px;">
						<el-checkbox></el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-col> -->
			<!-- <el-col :span="6">
				<el-form-item label="采购人">
					<el-input type="text" v-model="searchFormData.name" size="mini" clearable />
				</el-form-item>
			</el-col>
			<el-col :span="6">
				<el-form-item label="商品名称">
					<el-input type="text" v-model="searchFormData.goodsName" size="mini" clearable />
				</el-form-item>
			</el-col>
			<el-col :span="6">
				<el-form-item label="sku">
					<el-input type="text" v-model="searchFormData.sku" size="mini" clearable />
				</el-form-item>
			</el-col> -->
			<el-col :span="18">
				<el-button @click="sendHandle"  size="mini">批量发起对账
				</el-button>
				<el-button @click="refreshControlHandle" size="mini">重置</el-button>
				<el-button @click="searchControlHandle" size="mini">查询</el-button>
				<!-- <el-button @click="exportOrder" style="float: right;" size="mini">导出订单</el-button> -->
			</el-col>
		</el-form>
		<div class="table-box">
			<el-table :data="tableData" border :span-method="objectSpanMethod" @selection-change="handleSelectionChange"
				height="calc(100vh - 330px)" ref="multipleTable">
				<el-table-column type="selection" width="50" fixed="left"></el-table-column>
				<el-table-column label="序号" width="50" fixed="left">
					<template slot-scope="scope">
						{{scope.$index+1}}
					</template>
				</el-table-column>
				<el-table-column prop="orderNo" label="订单号" fixed="left" width="200">
				</el-table-column>
				<el-table-column prop="orderName" label="订单名称" fixed="left" width="200">
				</el-table-column>
				<el-table-column prop="sjorgname" label="上级采购组织" fixed="left" width="200">
				</el-table-column>
				<el-table-column prop="purchaseName" label="采购组织" fixed="left" width="200">
				</el-table-column>
				<el-table-column width="200" fixed="left">
					<template slot-scope="scope">
						<el-button size="mini" type="primary" @click="selectOne(scope.row)">发起对账</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="goodsName" label="商品名称" width="200">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.goodsName}}
					</template>
				</el-table-column>
				<el-table-column prop="sku" label="sku">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.sku}}
					</template>
				</el-table-column>
				<el-table-column prop="supplierTaxRate" label="税率">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.supplierTaxRate}}
					</template>
				</el-table-column>
				<el-table-column prop="price" label="含税单价">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.supPrice}}
					</template>
				</el-table-column>
				<el-table-column prop="excludeTaxPrice" label="未税单价">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.initExcludeTaxPrice}}
					</template>
				</el-table-column>
				<el-table-column prop="buyNum" label="数量">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.buyNum}}
					</template>
				</el-table-column>
				<el-table-column prop="budget" label="含税总价">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.budget}}
					</template>
				</el-table-column>
				<el-table-column prop="allExcludeTaxPrice" label="未税总价">
					<!-- ???? -->
					<template slot-scope="scope">
						{{scope.row.newquotaObj.allExcludeTaxPrice}}
					</template>
				</el-table-column>

				<el-table-column prop="specification" label="规格">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.unit}}
					</template>
				</el-table-column>
				<el-table-column prop="typeNo" label="型号">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.typeNo}}
					</template>
				</el-table-column>
				<el-table-column prop="supplierName" label="备注">
					<template slot-scope="scope">
						{{scope.row.newquotaObj.remark}}
					</template>
				</el-table-column>
			</el-table>

			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:page-size="pageData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageData.total"
				style="text-align: right;">
			</el-pagination>

		</div>



		<el-dialog title="批量对账" :visible.sync="remarkDialogShow" width="500px">
			<el-date-picker
			  v-model="edata"
			  type="date"
			  placeholder="选择日期">
			</el-date-picker>
			<div slot="footer" class="dialog-footer">
				<el-button @click="remarkDialogShow = false">取 消</el-button>
				<el-button type="primary" @click="apply(edata)">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="开票信息信息" :visible.sync="paperDialogShow" width="500px">
			<el-form label-position="'right'" label-width="120px" label-suffix=":">
				<el-form-item label="发票类型">
					<el-input v-if="paperDict.receiptType == 0" value="增值税普通发票" readonly="readonly" />
					<el-input v-if="paperDict.receiptType == 1" value="增值税专用发票" readonly="readonly" />
				</el-form-item>
				<el-form-item label="税号">
					<el-input v-model="paperDict.dutyParagraph" readonly="readonly" />
				</el-form-item>
				<el-form-item label="单位名称">
					<el-input v-model="paperDict.unitName" readonly="readonly" />
				</el-form-item>
				<el-form-item label="发票打印电话">
					<el-input v-model="paperDict.registrationTelephone" readonly="readonly" />
				</el-form-item>
				<el-form-item label="开户银行">
					<el-input v-model="paperDict.depositBank" readonly="readonly" />
				</el-form-item>
				<el-form-item label="银行账号">
					<el-input v-model="paperDict.accountNumber" readonly="readonly" />
				</el-form-item>
				<el-form-item label="发票打印地址">
					<el-input v-model="paperDict.registeredAddress" readonly="readonly" />
				</el-form-item>
			</el-form>
			<!-- <div slot="footer" class="dialog-footer">
					<el-button @click="paperDialogShow = false">取 消</el-button>
					<el-button type="primary" @click="submitHandle2()">确 定</el-button>
				</div> -->
		</el-dialog>
		
		<el-dialog title="错误信息" :visible.sync="errorDialogTableVisible">
		  <el-table :data="errData">
		    <el-table-column property="orderNo" label="订单号" width="150"></el-table-column>
		    <el-table-column property="sku" label="sku" width="200"></el-table-column>
		    <el-table-column property="error" label="失败原因"></el-table-column>
		  </el-table>
		</el-dialog>
	</div>
</template>

<script>
	import {
		findOrderDoReconciliation,
		findOrderCanReconciliation,
		setReceivingStatus,
		getUser,
		getTreceipt,
		getOrgLazyTree,
		getOrgLazyTree4,
		supplierReconciliationExport,
		supplierList
	} from '@/api/admin.api'
	import moment from 'moment'
	export default {
		name: 'supplierReconciliation',
		data() {
			return {
				searchFormData: {
					createTime: ['', ''],
					orgName:"",
					orgId:"",
					type:true,
					allCh:"",
					orderNo: undefined,
					supplierId: undefined
				},
				tableData: [],
				// 分页数据
				pageData: {
					// 当前分页
					pageNum: 1,
					// 分页条数
					pageSize: 10,
					// 数据总数
					total: 0,
				},
				// 表格选中数据
				tableSelectData: [],
				remarkDialogShow: false,
				paperDialogShow: false,
				remark: "",
				edata: "",
				paperDict: {},

				treeData: [],
				// 树配置项
				defaultProps: {
					children: 'children',
					label: 'name',
					isLeaf: 'leaf'
				},
				multipleSelection:[],
				errorDialogTableVisible: false,
				errData: [],
				supplierList: []
			}
		},
		methods: {
			clear(){
				var str = this.searchFormData.orgName;
				if(str.length == 0){
					this.treeData = [];
					this.searchFormData.orgId = '';
					this.searchFormData.orgName = '';
				}
			},
			getSupplierList() {
				supplierList().then(res => {
					this.supplierList = res
				})
			},
			 enterSearch:function(e){
			    if(e.keyCode === 13) {
			      console.log(11);
			      console.log(e.target.value);
				  
				  getOrgLazyTree4({
				  	id: e.target.value
				  }).then((data) => {
				  	console.log(data);
				  	this.treeData = data;
					this.$refs.selectReport.blur();
					var that = this;
					setTimeout(function() {
						  that.$refs.selectReport.focus();
					}, 300);
				  })
			    }
			  },
			dataFilter(val){
				console.log(val);
			},
			changeType(e){
				this.searchFormData.type = e;
			},
			blurOrg(e){
				// console.log(e);
				// console.log(e.target.value);
			},
			// 左侧树点击
			changeTree(item) {
				var that = this;
				that.searchFormData.orgName = item.name;
				that.searchFormData.orgId = item.id;
				that.searchFormData.allCh = item.allCh;
				that.$refs.selectReport.blur();
			},
			getOrgLazyTree() {
				var that = this;
				getOrgLazyTree({
					id: "0b655260fc9711ea99830242ac110002"
				}).then((data) => {
					console.log(data);
					that.treeData = data;
				})
			},
			// 组织机构节点数据
			loadNode(node, resolve) {
				if (node.level === 0) {
					// getOrgLazyTree({
					// 	id: "0b655260fc9711ea99830242ac110002"
					// }).then((res) => {
					// 	res.forEach(item => {
					// 		// 检查是否有叶子节点
					// 		item['leaf'] = false
					// 	})
					// 	if (res.length > 0) {
					// 		this.form = res[0];
					// 	}
					// 	return resolve(res)
					// })
				} else if (node.data.allCh) {
					getOrgLazyTree({
						id:node.data.id
					}).then((res) => {
						res.forEach(item => {
							// 检查是否有叶子节点
							item['leaf'] = !item.allCh
						})
						return resolve(res)
					})
				} else {
					return resolve([])
				}
			},
			getReturnNode(node, _array, value) {
				let isPass = node && node.label && node.label.indexOf(value) !== -1
				isPass ? _array.push(isPass) : ''
				if (!isPass && node.level != 1 && node.parent) {
					this.getReturnNode(node.parent, _array, value)
				}
			},
			//优化之后的代码 不管有几级都可以适用,不过用了递归
			filterNode(value, data, node) {
				console.log(value, data, node)
				if (!value) {
					return true
				}
				let _array = [] //这里使用数组存储 只是为了存储值。
				this.getReturnNode(node, _array, value)
				let result = false
				_array.forEach(item => {
					result = result || item
				})
				return result
			},
			getPaper(row) {
				var that = this;
				console.log(row);
				getTreceipt({
					id: row.mid
				}).then((res2) => {
					console.log(res2);
					that.paperDict = res2;
					that.paperDialogShow = true;
				})
			},
			changePeople(e) {
				console.log(e);
				var that = this;
				for (var i = 0; i < that.peopleList.length; i++) {
					if (e == that.peopleList[i].userId) {
						that.people.account = that.peopleList[i].account;
					}
				}
			},
			exportOrder() {
				var that = this;
				var type = this.searchFormData.type;
				const newSearch = {
					orderNo: this.searchFormData.orderNo,
					orderName: this.searchFormData.orderName,
					createTime1: this.searchFormData.createTime[0] ? moment(this.searchFormData.createTime[0]).format(
						'YYYY-MM-DD') : '',
					createTime2: this.searchFormData.createTime[1] ? moment(this.searchFormData.createTime[1]).format(
						'YYYY-MM-DD') : '',
					status: "未对账",
					eshopNumber: this.searchFormData.eshopNumber,
					goodsName: this.searchFormData.goodsName,
					sku: this.searchFormData.sku,
					name: this.searchFormData.name,
					orgName:this.searchFormData.orgName,
					type:this.searchFormData.type,
					...this.pageData,
				}
				if (type == false) {
					newSearch.orgId = "";
					// delete newSearch["orgId"];
					newSearch.allCh = this.searchFormData.allCh;
				} else {
					newSearch.allCh = "";
					// delete newSearch["allCh"];
					newSearch.orgId = this.searchFormData.orgId;
				}
				if (!this.searchFormData.orgId) {
					newSearch.allCh = this.searchFormData.temp;
				}
				console.log(newSearch);
				supplierReconciliationExport(newSearch).then((res) => {
					let url = window.URL.createObjectURL(new Blob([res], {type: "application/vnd.ms-excel"}))
					let link = document.createElement('a')
					link.style.display = 'none'
					link.href = url
					link.setAttribute('download', "采购组织对账.xlsx")
					document.body.appendChild(link)
					link.click()
					that.$message({
						type: 'success',
						message: '导出成功!'
					});
				})
			
			},
			submitHandle(remark) {
				var that = this;
				var arr = this.multipleSelection;
				if (arr.length <= 0) {
					return this.$message({
						type: 'error',
						message: '请选择操作行!'
					});
				}
				var list = [];
				for (var i = 0; i < arr.length; i++) {
					list.push({
						id: arr[i].newquotaObj.id,
						isReceipt: 1,
						remark: remark,
						status: "A1001"
					})
				}
				setReceivingStatus(list).then((res) => {
					console.log(res);
					this.$message({
						type: 'success',
						message: '对账成功!'
					});
					this.getTableData();
					this.remarkDialogShow = false;
				})
			},
			// 检索订单管理列表
			searchControlHandle() {
				// if (this.searchFormData.orgId) {
				// 	this.getTableData()
				// }else{
				// 	this.$message({
				// 		type: 'error',
				// 		message: '请选择采购组织!'
				// 	});
				// }
				this.getTableData()
			},
			handleSizeChange(val) {
				this.pageData.pageSize = val
				this.getTableData()
			},
			handleCurrentChange(val) {
				this.pageData.pageNum = val
				this.getTableData()
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			sendHandle() {
				var arr = this.multipleSelection;
				if (arr.length <= 0) {
					return this.$message({
						type: 'error',
						message: '请选择操作行!'
					});
				}
				this.remarkDialogShow = true;
			},
			objectSpanMethod({
				row,
				column,
				rowIndex,
				columnIndex
			}) {
				let addIndex = 0;
				if (columnIndex > 0 && columnIndex < 6) {
					if (rowIndex == row.numAll) {
						return {
							rowspan: row.lengthNum,
							colspan: 1,
						};
					} else {
						return {
							rowspan: 0,
							colspan: 0,
						};
					}
				} else {
					return {
						rowspan: 1,
						colspan: 1,
					};
				}
			},
			// 重置搜索条件
			refreshControlHandle() {
				this.searchFormData = {
					createTime: ['', '']
				}
				this.getTableData();
			},
			// 请求订单管理列表
			getTableData() {
				if(this.searchFormData.supplierId == undefined) {
					this.$message.warning({message: "请选择一个供应商"})
					return;
				}
				var type = this.searchFormData.type;
				var newSearch = {
					orderNo: this.searchFormData.orderNo,
					orderName: this.searchFormData.orderName,
					createTime1: this.searchFormData.createTime[0] ? moment(this.searchFormData.createTime[0]).format(
						'YYYY-MM-DD') : '',
					createTime2: this.searchFormData.createTime[1] ? moment(this.searchFormData.createTime[1]).format(
						'YYYY-MM-DD') : '',
					status: "未对账",
					eshopNumber: this.searchFormData.eshopNumber,
					goodsName: this.searchFormData.goodsName,
					sku: this.searchFormData.sku,
					name: this.searchFormData.name,
					orgName:this.searchFormData.orgName,
					type:this.searchFormData.type,
					...this.pageData,
					supplierId: this.searchFormData.supplierId,
				}
				if(type == false){
					newSearch.orgId = "";
					newSearch.allCh = this.searchFormData.allCh;
				}else{
					newSearch.allCh = "";
					newSearch.orgId = this.searchFormData.orgId;
				}
				
				findOrderCanReconciliation(newSearch).then((res) => {
					let tableData = res.rows;
					let newArr = [];
					let numAll = 0;
					for (let i = 0; i < tableData.length; i++) {
						for (let j = 0; j < tableData[i].detail.length; j++) {
							newArr.push({
								...tableData[i],
								newquotaObj: tableData[i].detail[j],
								lengthNum: tableData[i].detail.length,
								numAll,
							});
						}
						numAll = numAll + tableData[i].detail.length;
					}
					this.tableData = newArr;
					this.pageData.total = res.total;
				})

			},
			selectOne(row) {
				this.$refs.multipleTable.clearSelection();
				this.$refs.multipleTable.toggleRowSelection(row);
				this.multipleSelection = [row];
				this.sendHandle();
			},
			// 发起对账
			apply(edata) {
				const info = [];
				const obj = {};
				if(this.multipleSelection.length > 20) {
					this.$message.warning({
						message: "每次只能提交20个订单，自动忽略超出的订单"
					})
				}
				this.multipleSelection.forEach((row, index) => {
					if(index < 20) {
						obj.sku = row.newquotaObj.sku
						obj.orderNo = row.orderNo
						obj.edate = edata
						obj.buyNum = row.newquotaObj.buyNum
						info.push({...obj})
					}
				})
				findOrderDoReconciliation(info).then(res => {
					const err = [];
					const obj = {};
					res.forEach(row => {
						if(!row.success) {
							obj.orderNo = row.orderNo
							obj.sku = row.sku
							obj.error = row.error
							err.push({...obj})
						}
					})
					this.errData = err;
					if(err.length < 1) {
						this.$message.success("提交成功")
					}else {
						this.errorDialogTableVisible = true;
					}
					this.remarkDialogShow = false;
					this.getTableData();
				})
				this.$refs.multipleTable.clearSelection();
			},
			changeSupplier() {
				this.getTableData();
			}
		},
		created() {},
		mounted() {
			window.addEventListener("keyup",this.enterSearch)
			this.getSupplierList();
		},
	}
</script>

<style>
	.el-button--text {
		display: none;
	}
</style>
